package net.hn.hnms.biz.safety.monitor.group.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.mine.RemoteEquipmentService;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.mine.model.FanSystemVolumeAndSpeedDto;
import net.hn.hnms.biz.api.mine.model.dto.MineCodeMapDto;
import net.hn.hnms.biz.api.safety.dust.fegin.RemoteDustService;
import net.hn.hnms.biz.api.safety.fire.fegin.RemoteFrieService;
import net.hn.hnms.biz.api.safety.gasext.domain.DimCoalMineBasicInfoVo;
import net.hn.hnms.biz.api.safety.gasext.domain.TransfiniteStatisticsVo;
import net.hn.hnms.biz.api.safety.gasext.fegin.RemoteDwsService;
import net.hn.hnms.biz.api.safety.location.model.GroupAlarmDataTotal;
import net.hn.hnms.biz.api.safety.location.model.GroupAlarmDataVo;
import net.hn.hnms.biz.api.safety.monitor.model.MonitorTodayInfo;
import net.hn.hnms.biz.api.safety.monitor.model.MonitorTodayInfoTotal;
import net.hn.hnms.biz.api.safety.monitor.model.PointStatistics;
import net.hn.hnms.biz.api.safety.support.domain.MineNowAlarmVo;
import net.hn.hnms.biz.api.safety.support.fegin.RemoteSupportService;
import net.hn.hnms.biz.api.safety.water.fegin.RemoteWaterService;
import net.hn.hnms.biz.safety.monitor.company.service.CompanyMonitorService;
import net.hn.hnms.biz.safety.monitor.domain.LongruanAlarmListPo;
import net.hn.hnms.biz.safety.monitor.domain.vo.NowSensorAlarmVo;
import net.hn.hnms.biz.safety.monitor.group.entity.*;
import net.hn.hnms.biz.safety.monitor.group.entity.dto.FanSystemDeviceDto;
import net.hn.hnms.biz.safety.monitor.group.entity.dto.MineDataResponse;
import net.hn.hnms.biz.safety.monitor.group.entity.dto.OtherApiAqjkNowCountDto;
import net.hn.hnms.biz.safety.monitor.group.entity.dto.OtherApiAqjkNowDto;
import net.hn.hnms.biz.safety.monitor.mapper.LongruanAlarmListMapper;
import net.hn.hnms.biz.safety.monitor.service.SafetyMonitorService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.constant.MineBaseConstants;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.redis.domain.SysOrganizationVo;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 智呈物联 pan'sx
 * 2022/12/21 13:37
 * 1.0 version
 */
@Service
@RequiredArgsConstructor
public class GroupMonitorService {
    private final JdbcTemplate monitorJdbcTemplate;
    private final RemoteSupportService remoteSupportService;
    private final RemoteWaterService remoteWaterService;
    private final RemoteDustService remoteDustService;
    private final RemoteFrieService remoteFrieService;

    //远程调用智慧煤矿服务
    @Resource
    private RemoteMineInfoService remoteMineInfoService;

    //安全监控服务
    @Resource
    private SafetyMonitorService safetyMonitorService;
    /**
     * 公司端服务
     */
    @Resource
    private CompanyMonitorService companyMonitorService;

    @Resource
    private LongruanAlarmListMapper longruanAlarmListMapper;

    @Resource
    private RemoteEquipmentService remoteEquipmentService;

    @Resource
    private RemoteDwsService dwsService;

    public MonitorTodayInfoTotal riskSituation(String companyCode) {

        String where;
        if (StringUtils.isNotBlank(companyCode)) {
            where = " and company_code='" + companyCode + "'";
        } else {
            where = "";
        }
        String sql = "SELECT COUNT\n" +
                "	( 1 ) AS COUNT,\n" +
                "	alramlevel AS alram_level,\n" +
                "	sensor_type,\n" +
                "	mine_code\n" +
                "FROM\n" +
                "	(\n" +
                "	SELECT\n" +
                "	mine_code,\n" +
                "	CASE\n" +
                "			sensor_type \n" +
                "			WHEN '0004' THEN\n" +
                "		CASE\n" +
                "				\n" +
                "				WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 900 THEN\n" +
                "			CASE\n" +
                "					\n" +
                "					WHEN ( max_value < 50 AND max_value >= 24 ) THEN\n" +
                "					'蓝色预警' \n" +
                "					WHEN ( max_value < 90 AND max_value >= 50 ) THEN\n" +
                "					'蓝色预警' \n" +
                "					WHEN ( max_value < 200 AND max_value >= 90 ) THEN\n" +
                "					'黄色预警' \n" +
                "					WHEN ( max_value >= 200 ) THEN\n" +
                "					'橙色预警' \n" +
                "				END \n" +
                "					WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 1500 AND EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 900 THEN\n" +
                "				CASE\n" +
                "						\n" +
                "						WHEN ( max_value < 50 AND max_value >= 24 ) THEN\n" +
                "						'蓝色预警' \n" +
                "						WHEN ( max_value < 90 AND max_value >= 50 ) THEN\n" +
                "						'黄色预警' \n" +
                "						WHEN ( max_value < 200 AND max_value >= 90 ) THEN\n" +
                "						'黄色预警' \n" +
                "						WHEN ( max_value >= 200 ) THEN\n" +
                "						'橙色预警' \n" +
                "					END \n" +
                "						WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 1800 AND EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 1500 THEN\n" +
                "					CASE\n" +
                "							\n" +
                "							WHEN ( max_value < 50 AND max_value >= 24 ) THEN\n" +
                "							'黄色预警' \n" +
                "							WHEN ( max_value < 90 AND max_value >= 50 ) THEN\n" +
                "							'黄色预警' \n" +
                "							WHEN ( max_value < 200 AND max_value >= 90 ) THEN\n" +
                "							'橙色预警' \n" +
                "							WHEN ( max_value >= 200 ) THEN\n" +
                "							'红色预警' \n" +
                "						END \n" +
                "							WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 1800 THEN\n" +
                "						CASE\n" +
                "								\n" +
                "								WHEN ( max_value < 50 AND max_value >= 24 ) THEN\n" +
                "								'黄色预警' \n" +
                "								WHEN ( max_value < 90 AND max_value >= 50 ) THEN\n" +
                "								'橙色预警' \n" +
                "								WHEN ( max_value < 200 AND max_value >= 90 ) THEN\n" +
                "								'红色预警' \n" +
                "								WHEN ( max_value >= 200 ) THEN\n" +
                "								'红色预警' \n" +
                "							END \n" +
                "							END \n" +
                "								WHEN '0001' THEN\n" +
                "							CASE\n" +
                "									\n" +
                "									WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 900 THEN\n" +
                "								CASE\n" +
                "										\n" +
                "										WHEN ( max_value < 1 AND max_value >= 0.5 ) THEN\n" +
                "										'蓝色预警' \n" +
                "										WHEN ( max_value < 1.5 AND max_value >= 1 ) THEN\n" +
                "										'蓝色预警' \n" +
                "										WHEN ( max_value < 2 AND max_value >= 1.5 ) THEN\n" +
                "										'黄色预警' \n" +
                "										WHEN ( max_value >= 2 ) THEN\n" +
                "										'橙色预警' \n" +
                "									END \n" +
                "										WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 1500 AND EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 900 THEN\n" +
                "									CASE\n" +
                "											\n" +
                "											WHEN ( max_value < 1 AND max_value >= 0.5 ) THEN\n" +
                "											'蓝色预警' \n" +
                "											WHEN ( max_value < 1.5 AND max_value >= 1 ) THEN\n" +
                "											'黄色预警' \n" +
                "											WHEN ( max_value < 2 AND max_value >= 1.5 ) THEN\n" +
                "											'黄色预警' \n" +
                "											WHEN ( max_value >= 2 ) THEN\n" +
                "											'橙色预警' \n" +
                "										END \n" +
                "											WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) <= 1800 AND EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 1500 THEN\n" +
                "										CASE\n" +
                "												\n" +
                "												WHEN ( max_value < 1 AND max_value >= 0.5 ) THEN\n" +
                "												'黄色预警' \n" +
                "												WHEN ( max_value < 1.5 AND max_value >= 1 ) THEN\n" +
                "												'黄色预警' \n" +
                "												WHEN ( max_value < 2 AND max_value >= 1.5 ) THEN\n" +
                "												'橙色预警' \n" +
                "												WHEN ( max_value >= 2 ) THEN\n" +
                "												'红色预警' \n" +
                "											END \n" +
                "												WHEN EXTRACT ( epoch FROM ( end_time - begin_time ) ) > 1800 THEN\n" +
                "											CASE\n" +
                "													\n" +
                "													WHEN ( max_value < 1 AND max_value >= 0.5 ) THEN\n" +
                "													'黄色预警' \n" +
                "													WHEN ( max_value < 1.5 AND max_value >= 1 ) THEN\n" +
                "													'橙色预警' \n" +
                "													WHEN ( max_value < 2 AND max_value >= 1.5 ) THEN\n" +
                "													'红色预警' \n" +
                "													WHEN ( max_value >= 2 ) THEN\n" +
                "													'红色预警' \n" +
                "												END \n" +
                "												END \n" +
                "												END AS alramLevel,\n" +
                "												sensor_type,\n" +
                "											ID \n" +
                "											FROM\n" +
                "												dwd_aqjk_now_sensoralarm_count_stat \n" +
                "											WHERE\n" +
                "												( sensor_type = '0004' OR sensor_type = '0001' ) \n" +
                "												AND end_time IS NOT NULL \n" +
                "												AND max_value IS NOT NULL \n" +
                "												AND ( end_time > CURRENT_DATE OR begin_time > CURRENT_DATE ) \n" +
                "												AND outlier_type = '001' %s \n" +
                "											) T \n" +
                "										GROUP BY\n" +
                "										alramlevel,\n" +
                "										sensor_type,\n" +
                "										 mine_code";
        List<MonitorTodayInfo> list = new ArrayList<>();
        MonitorTodayInfoTotal total = new MonitorTodayInfoTotal();
        for (String key : MineBaseConstants.mineMap.keySet()) {
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
                continue;
            }
            MonitorTodayInfo monitorTodayInfo = new MonitorTodayInfo();
            MonitorTodayInfo.Item itemBlue = monitorTodayInfo.new Item();
            itemBlue.setCh4(0L);
            itemBlue.setCo(0L);
            MonitorTodayInfo.Item itemYellow = monitorTodayInfo.new Item();
            itemYellow.setCh4(0L);
            itemYellow.setCo(0L);
            MonitorTodayInfo.Item itemOrange = monitorTodayInfo.new Item();
            itemOrange.setCh4(0L);
            itemOrange.setCo(0L);
            MonitorTodayInfo.Item itemRed = monitorTodayInfo.new Item();
            itemRed.setCh4(0L);
            itemRed.setCo(0L);
            BeanUtils.copyProperties(mine, monitorTodayInfo);
            monitorTodayInfo.setBlue(itemBlue);
            monitorTodayInfo.setOrange(itemOrange);
            monitorTodayInfo.setRed(itemRed);
            monitorTodayInfo.setYellow(itemYellow);
            list.add(monitorTodayInfo);
        }
        total.setMonitorTodayInfos(list);
        List<Map<String, Object>> maps = monitorJdbcTemplate.queryForList(String.format(sql, where));

        for (Map<String, Object> map : maps) {
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(map.get("mine_code"));
            if (mine != null) {
                MonitorTodayInfo monitorTodayInfo = new MonitorTodayInfo();
                monitorTodayInfo.setMineCode(mine.getMineCode());
                MonitorTodayInfo info = list.get(list.indexOf(monitorTodayInfo));
                if ("蓝色预警".equals(map.get("alram_level"))) {
                    if ("0004".equals(map.get("sensor_type"))) {
                        info.getBlue().setCo((Long) map.get("count"));
                    } else {
                        info.getBlue().setCh4((Long) map.get("count"));
                    }
                    info.getBlue().addCount();
                    total.setBlue(total.getBlue() + (Long) map.get("count"));
                } else if ("黄色预警".equals(map.get("alram_level"))) {
                    if ("0004".equals(map.get("sensor_type"))) {
                        info.getYellow().setCo((Long) map.get("count"));
                    } else {
                        info.getYellow().setCh4((Long) map.get("count"));
                    }
                    info.getYellow().addCount();
                    total.setYellow(total.getYellow() + (Long) map.get("count"));
                } else if ("橙色预警".equals(map.get("alram_level"))) {
                    if ("0004".equals(map.get("sensor_type"))) {
                        info.getOrange().setCo((Long) map.get("count"));
                    } else {
                        info.getOrange().setCh4((Long) map.get("count"));
                    }
                    info.getOrange().addCount();
                    total.setOrange(total.getOrange() + (Long) map.get("count"));
                } else if ("红色预警".equals(map.get("alram_level"))) {
                    if ("0004".equals(map.get("sensor_type"))) {
                        info.getRed().setCo((Long) map.get("count"));
                    } else {
                        info.getRed().setCh4((Long) map.get("count"));
                    }
                    info.getRed().addCount();
                    total.setRed(total.getRed() + (Long) map.get("count"));
                }
            }
        }
        return total;
    }

    public GroupAlarmDataTotal alarm(String companyCode) {
        String where;
        if (StringUtils.isNotBlank(companyCode)) {
            where = " and company_code='" + companyCode + "'";
        } else {
            where = "";
        }
        GroupAlarmDataTotal total = new GroupAlarmDataTotal();
        List<GroupAlarmDataVo> list = new ArrayList<>();
        total.setList(list);
        for (String key : MineBaseConstants.mineMap.keySet()) {
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(key);
            if (StringUtils.isNotBlank(companyCode)&&!mine.getCompanyCode().equals(companyCode)) {
                continue;
            }
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            BeanUtils.copyProperties(mine, vo);
            list.add(vo);
        }
        String sql = "SELECT mine_code,\"count\"(1) count FROM \"dwd_aqjk_now_sensoralarm_count_stat\" where  (end_time>CURRENT_DATE  or begin_time>CURRENT_DATE ) GROUP BY mine_code";
        List<Map<String, Object>> maps = monitorJdbcTemplate.queryForList(String.format(sql, where));
        for (Map<String, Object> map : maps) {
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            vo.setMineCode(map.get("mine_code") + "");
            GroupAlarmDataVo info = list.get(list.indexOf(vo));
            info.setAqjk(Integer.parseInt(map.get("count") + ""));
            total.setAqjk(total.getAqjk() + info.getAqjk());
        }
        List<MineNowAlarmVo> mineNowAlarmVos = remoteSupportService.nowAlarm("", companyCode);
        for (MineNowAlarmVo alarmVo : mineNowAlarmVos) {
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            vo.setMineCode(alarmVo.getMineCode());
            GroupAlarmDataVo info = list.get(list.indexOf(vo));
            info.setDbzh(alarmVo.getCount());
            total.setDbzh(total.getDbzh() + info.getDbzh());
        }
        List<MineNowAlarmVo> waterAlarms = remoteWaterService.nowAlarm();
        for (MineNowAlarmVo alarmVo : waterAlarms) {
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            vo.setMineCode(alarmVo.getMineCode());
            GroupAlarmDataVo info = list.get(list.indexOf(vo));
            info.setShfz(alarmVo.getCount());
            total.setShfz(total.getShfz() + info.getShfz());
        }
        List<MineNowAlarmVo> dustAlarms = remoteDustService.alarmByMine();
        for (MineNowAlarmVo alarmVo : dustAlarms) {
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            vo.setMineCode(alarmVo.getMineCode());
            GroupAlarmDataVo info = list.get(list.indexOf(vo));
            info.setFcfz(alarmVo.getCount());
            total.setFcfz(total.getFcfz() + info.getFcfz());
        }
        List<MineNowAlarmVo> fireAlarms = remoteFrieService.nowAlarm();
        for (MineNowAlarmVo alarmVo : fireAlarms) {
            GroupAlarmDataVo vo = new GroupAlarmDataVo();
            vo.setMineCode(alarmVo.getMineCode());
            GroupAlarmDataVo info = list.get(list.indexOf(vo));
            info.setHzfz(alarmVo.getCount());
            total.setHzfz(total.getHzfz() + info.getHzfz());
        }
        return total;
    }


    /**
     * 根据气体获取当天实时传感器报警
     * @param gasesTypeName
     * @return
     */
    public List<NowSensorAlarmVo> getTodayNowSensorAlarmByGases(String gasesTypeName) {
        //获取当前公司的所有煤矿
        SysOrganizationVo sysOrganizationVo = RedisUtils.getCacheObject(Constants.SYS_CODESUB_KEY + 0);
        if (sysOrganizationVo == null) {
            throw new HuaNengException(Constants.FAIL, "无法获集团的子煤矿信息，请检查词典");
        }
        List<NowSensorAlarmVo> voList = new ArrayList<>();
        for (SysOrganizationVo organizationVo : sysOrganizationVo.getSubCodeList()) {
            //遍历集团所有公司
            List<NowSensorAlarmVo> list = companyMonitorService.getTodayNowSensorAlarmByGases(organizationVo.getOrgCode(), gasesTypeName);
            for (NowSensorAlarmVo nowSensorAlarmVo : list) {
                voList.add(nowSensorAlarmVo);
            }
        }
        return voList;
    }

    /**
     * 大屏首页-安全检测
     * @return
     */
    public SafetyMonitoringVo getSafetyMonitoring() {
        //获取龙软煤矿数据
        MineDataResponse<List<OtherApiAqjkNowDto>> otherSystemGroupAqjkNowApi = this.getOtherSystemGroupAqjkNowApi();
        //龙软安全监控实时数据
        List<OtherApiAqjkNowDto> aqjkNowApiData = null;
        if (otherSystemGroupAqjkNowApi.isSuccess()) {

            aqjkNowApiData = otherSystemGroupAqjkNowApi.getData();
        } else {
            aqjkNowApiData = new ArrayList<>();
        }

        //转成map
        Map<String, OtherApiAqjkNowDto> otherApiAqjkNowDtoMap = aqjkNowApiData.stream().collect(Collectors.toMap(OtherApiAqjkNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiAqjkNowDto())));

        //获取华能龙软映射表信息
        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");

        // 需要删除的煤矿编码列表（去除露天矿） 魏家峁 铧尖 伊敏
        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList);

        //去除 测点数为零的煤矿
        mineCodeMapList = mineCodeMapList.stream().filter(t -> {
        //获取龙软数据
            OtherApiAqjkNowDto otherApiAqjkNowDto = otherApiAqjkNowDtoMap.get(t.getMineId());
            if (otherApiAqjkNowDto != null  && otherApiAqjkNowDto.getSensorCount() > 0) {
                return true;
            }
            return false;

        }).collect(Collectors.toList());
        //煤矿报警列表
        List<MinePointInAlarmfoVo> minePointInAlarmfoVoList = mineCodeMapList.stream().map(t -> {
            MinePointInAlarmfoVo minePointInAlarmfoVo = new MinePointInAlarmfoVo();
            minePointInAlarmfoVo.setMineCode(t.getMineCode());
            minePointInAlarmfoVo.setMineName(t.getMineName());
            //龙软煤矿数据
            OtherApiAqjkNowDto otherApiAqjkNowDto = otherApiAqjkNowDtoMap.get(t.getMineId());
            if (otherApiAqjkNowDto != null) {
                //TODO 屏蔽掉雨汪煤矿（10105087403）和新庄煤矿（01001002014）的报警值
                if ("10105087403".equals(otherApiAqjkNowDto.getMineID()) || "01001002014".equals(otherApiAqjkNowDto.getMineID())) {
                    otherApiAqjkNowDto.setCoWarnCount(0);
                    otherApiAqjkNowDto.setCH4WarnCount(0);

                }
                //设置测点数据
                minePointInAlarmfoVo.setPointNumber(otherApiAqjkNowDto.getSensorCount());
                minePointInAlarmfoVo.setCH4WarnCount(otherApiAqjkNowDto.getCH4WarnCount());
                minePointInAlarmfoVo.setCoWarnCount(otherApiAqjkNowDto.getCoWarnCount());
                minePointInAlarmfoVo.setRemark(t.getMineId());
            } else {
                //查询华能的报警数据
                List<PointStatistics> pointStatistics = safetyMonitorService.pointStatistics(t.getMineCode());
                if (pointStatistics.isEmpty()) {
                    //如果是空值 则设置默认值为零
                    minePointInAlarmfoVo.setPointNumber(0);
                    minePointInAlarmfoVo.setCH4WarnCount(0);
                    minePointInAlarmfoVo.setCoWarnCount(0);
                    minePointInAlarmfoVo.setRemark(t.getMineCode());
                } else {
                    //获取甲烷信息。
                    //转成map
                    //环境瓦斯	54	0
                    //氧气	10	0
                    //烟雾	17	0
                    //粉尘	6	0
                    //风速	7	0
                    //湿度	2	0
                    //一氧化碳	50	0
                    //环境温度	51	0
                    Map<String, PointStatistics> pointStatisticsMap = pointStatistics.stream().collect(Collectors.toMap(PointStatistics::getType, p -> Optional.ofNullable(p).orElse(new PointStatistics())));

                    //获取甲烷信息
                    PointStatistics pointStatisticsItemCH4 = pointStatisticsMap.get("环境瓦斯");
                    if (pointStatisticsItemCH4 == null) {
                        pointStatisticsItemCH4 = new PointStatistics();
                    }
                    //设置甲烷数
                    minePointInAlarmfoVo.setCH4WarnCount(Optional.ofNullable(pointStatisticsItemCH4.getAlarmCount()).orElse(0));
                    //获取一氧化碳信息
                    PointStatistics pointStatisticsItemCO = pointStatisticsMap.get("一氧化碳");
                    if (pointStatisticsItemCO == null) {
                        pointStatisticsItemCO = new PointStatistics();
                    }
                    minePointInAlarmfoVo.setCoWarnCount(Optional.ofNullable(pointStatisticsItemCO.getAlarmCount()).orElse(0));
                    //设置测点总数   甲烷测点数+一氧化碳测点数
                    int sum = pointStatisticsItemCH4.getPointCount() + pointStatisticsItemCO.getPointCount();
                    minePointInAlarmfoVo.setPointNumber(sum);
                    minePointInAlarmfoVo.setRemark(t.getMineCode()+
                            "-"+pointStatisticsItemCH4.getType()+":"+pointStatisticsItemCH4.getPointCount()+
                            "-"+pointStatisticsItemCO.getType()+":"+pointStatisticsItemCO.getPointCount());
                }

            }

            //设置报警数都为零
            minePointInAlarmfoVo.setCH4WarnCount(0);
            minePointInAlarmfoVo.setCoWarnCount(0);

            return minePointInAlarmfoVo;
        }).collect(Collectors.toList());

        //计算测点总数
        int pointNumberSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getPointNumber)
                .sum();

        //计算CH4超限数
        int cH4WarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCH4WarnCount)
                .sum();
        //计算CO超限数
        int coWarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCoWarnCount)
                .sum();

        SafetyMonitoringVo vo = new SafetyMonitoringVo();

        //获取龙软安全监控测点接口
        MineDataResponse<OtherApiAqjkNowCountDto> otherSystemGroupAqjkCountNowApi = this.getOtherSystemGroupAqjkCountNowApi();

        OtherApiAqjkNowCountDto otherApiAqjkNowCountDto = otherSystemGroupAqjkCountNowApi.getData();
        if (otherApiAqjkNowCountDto != null) {
            vo.setCH4Number(otherApiAqjkNowCountDto.getGasCount());
            vo.setCoNumber(otherApiAqjkNowCountDto.getCoCount());
        } else {
            //CH4测点数
            vo.setCH4Number(0);
            //CO测点数
            vo.setCoNumber(0);
        }
        //煤矿测点信息列表
        vo.setMinePointInAlarmfoList(minePointInAlarmfoVoList);
        //测点总数
        vo.setPonitSum(pointNumberSum);
        //CH4超限报警数
//        vo.setCH4WarnCount(cH4WarnCountSum);
        vo.setCH4WarnCount(0);
        //CO超限报警数
//        vo.setCoWarnCount(coWarnCountSum);
        vo.setCoWarnCount(0);
        return vo;
    }

    @NotNull
    private static List<MineCodeMapDto> getRemoveMineCodeList(List<MineCodeMapDto> mineCodeMapList) {
        //（去除露天矿） 魏家峁 铧尖 伊敏

        List<String> codesToRemove = Arrays.asList("150622004330", "150622004317", "150724019283");
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !codesToRemove.contains(dto.getMineCode()))
                .collect(Collectors.toList());
        return mineCodeMapList;
    }
    @NotNull
    private static List<MineCodeMapDto> getRemoveMineCodeList(List<MineCodeMapDto> mineCodeMapList,List<String> mineCodeList) {
        List<String> codesToRemove = mineCodeList;
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !codesToRemove.contains(dto.getMineCode()))
                .collect(Collectors.toList());
        return mineCodeMapList;
    }


    //获取龙软安全监控实时接口
    public MineDataResponse<List<OtherApiAqjkNowDto>> getOtherSystemGroupAqjkNowApi() {
        String url = "http://10.103.9.31/pddP/PDDPAPI/GetRealtimeoverview";
        try {
            //井下实时总人数(各矿一条统计数据)

            MineDataResponse<List<OtherApiAqjkNowDto>> listMineDataResponse = sendGetRequest(url, "", new TypeReference<MineDataResponse<List<OtherApiAqjkNowDto>>>() {});

//            String responseData = "{ \"success\": true, \"data\": [ { \"MineID\": \"10100102901\", \"MineName\": \"青岗坪煤矿\", \"SensorCount\": 171, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10100102902\", \"MineName\": \"西川煤矿\", \"SensorCount\": 209, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10100109103\", \"MineName\": \"柳巷煤矿\", \"SensorCount\": 137, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10105087403\", \"MineName\": \"雨汪煤矿一井\", \"SensorCount\": 374, \"WarnCount\": 310, \"CoWarnCount\": 13, \"CH4WarnCount\": 63 }, { \"MineID\": \"10105087401\", \"MineName\": \"白龙山煤矿一井\", \"SensorCount\": 275, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10103047001\", \"MineName\": \"灵泉矿\", \"SensorCount\": 153, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10103047003\", \"MineName\": \"铁北矿\", \"SensorCount\": 112, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10103047006\", \"MineName\": \"灵东矿\", \"SensorCount\": 207, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"10103047007\", \"MineName\": \"灵露矿\", \"SensorCount\": 138, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"01002004001\", \"MineName\": \"高头窑煤矿\", \"SensorCount\": 0, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272502\", \"MineName\": \"华亭煤矿\", \"SensorCount\": 204, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272501\", \"MineName\": \"砚北煤矿\", \"SensorCount\": 341, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272503\", \"MineName\": \"陈家沟煤矿\", \"SensorCount\": 244, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272504\", \"MineName\": \"东峡煤矿\", \"SensorCount\": 217, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272507\", \"MineName\": \"山寨煤矿\", \"SensorCount\": 160, \"WarnCount\": 4, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272505\", \"MineName\": \"马蹄沟煤矿\", \"SensorCount\": 74, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272508\", \"MineName\": \"新窑公司\", \"SensorCount\": 162, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272509\", \"MineName\": \"新柏公司\", \"SensorCount\": 164, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272511\", \"MineName\": \"大柳煤矿\", \"SensorCount\": 182, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"62272512\", \"MineName\": \"赤城煤矿\", \"SensorCount\": 190, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"01001002013\", \"MineName\": \"核桃峪煤矿\", \"SensorCount\": 230, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"01001002014\", \"MineName\": \"新庄煤矿\", \"SensorCount\": 140, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 }, { \"MineID\": \"01001002015\", \"MineName\": \"刘园子煤矿\", \"SensorCount\": 84, \"WarnCount\": 0, \"CoWarnCount\": 0, \"CH4WarnCount\": 0 } ], \"message\": \"成功\" }";
//            String responseData = "{ \"success\": false, \"data\": null, \"message\": \"MyError:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - 无法打开到 SQL Server 的连接)\" }";

//            MineDataResponse<List<OtherApiAqjkNowDto>> listMineDataResponse = new ObjectMapper().readValue(responseData.toString(), new TypeReference<MineDataResponse<List<OtherApiAqjkNowDto>>>(){});
            return listMineDataResponse;
        } catch (IOException e) {
            throw new HuaNengException(Constants.FAIL, "远程调用龙软接口失败：" + url);
        }
    }

    /**
     * 获取安全监控测点数量
     * @return
     */
    public MineDataResponse<OtherApiAqjkNowCountDto> getOtherSystemGroupAqjkCountNowApi() {
        String url = "http://10.103.9.31/pddP/PDDPAPI/SensorCount";
        try {
            //井下实时总人数(各矿一条统计数据)

//            MineDataResponse<OtherApiAqjkNowCountDto> listMineDataResponse = sendGetRequest(url, "", new TypeReference<MineDataResponse<OtherApiAqjkNowCountDto>>() {});

            String responseData = "{ \"success\": true, \"data\": { \"COCount\": 549, \"GasCount\": 727, \"TemperatureCount\": 457, \"SmokeCount\": 356, \"DustCount\": 76, \"AllCount\": 4220 }, \"message\": \"测点数量查询成功\" }";
//            String responseData = "{ \"success\": false, \"data\": null, \"message\": \"MyError:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - 无法打开到 SQL Server 的连接)\" }";

//            ObjectMapper objectMapper = new ObjectMapper();
            MineDataResponse<OtherApiAqjkNowCountDto> listMineDataResponse = new ObjectMapper().readValue(responseData.toString(), new TypeReference<MineDataResponse<OtherApiAqjkNowCountDto>>(){});
            return listMineDataResponse;
        } catch (IOException e) {
            throw new HuaNengException(Constants.FAIL, "远程调用龙软接口失败：" + url);
        }
    }

    //发送get请求
    public static <T> T sendGetRequest(String url,String appToken,  TypeReference<T> responseType) throws IOException {
        // 创建URL对象
        URL apiUrl = new URL(url);

        // 打开HTTP连接
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 设置请求头
        connection.setRequestProperty("appToken", appToken);

        connection.setRequestProperty("Content-Type", "application/json");

        // 设置请求方法
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseData = new StringBuilder();

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                responseData.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 将JSON字符串解析为对象
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseData.toString(), responseType);
        }
        return null;
    }

    /**
     * 大屏首页-超限统计
     * @return
     */
    public TransfiniteStatisticsVo getTransfiniteStatistics(String type) {
        List<LongruanAlarmListPo> list = new ArrayList<>();
        if (StringUtils.isBlank(type)) {
            //空的
            //获取安全监控报警最近十天内的超限
            list =longruanAlarmListMapper.selectListMaxAlarmList();
        } else if ("周".equals(type)) {
            list =longruanAlarmListMapper.selectListWeekMaxAlarmList();
        } else if ("月".equals(type)) {
            list =longruanAlarmListMapper.selectListMonthMaxAlarmList();
        } else {
            return new TransfiniteStatisticsVo();
        }

        //时间
        List<LocalDate> dates = new ArrayList<>();
        //甲烷
        List<Integer> cH4WarnCountList = new ArrayList<>();
        //一氧化碳
        List<Integer> coWarnCountList = new ArrayList<>();

        for (LongruanAlarmListPo longruanAlarmListPo : list) {
            dates.add(LocalDateTime.ofInstant(longruanAlarmListPo.getDataTime().toInstant(), ZoneId.systemDefault()).toLocalDate());
            cH4WarnCountList.add(longruanAlarmListPo.getCh4WarnCount());
            coWarnCountList.add(longruanAlarmListPo.getCoWarnCount());
        }
        TransfiniteStatisticsVo transfiniteStatisticsVo = new TransfiniteStatisticsVo();
        transfiniteStatisticsVo.setDate(dates);
        transfiniteStatisticsVo.setCH4WarnCount(cH4WarnCountList);
        transfiniteStatisticsVo.setCoWarnCount(coWarnCountList);
        return transfiniteStatisticsVo;
    }

    /**
     * 大屏首页-安全监测联网情况
     * @return
     */
    public OnLineMineInfoVo getOnLineMineInfo() {
//        //获取龙软煤矿数据
//        MineDataResponse<List<OtherApiAqjkNowDto>> otherSystemGroupAqjkNowApi = this.getOtherSystemGroupAqjkNowApi();
//        //龙软安全监控实时数据
//        List<OtherApiAqjkNowDto> aqjkNowApiData = null;
//        if (otherSystemGroupAqjkNowApi.isSuccess()) {
//            aqjkNowApiData = otherSystemGroupAqjkNowApi.getData();
//        } else {
//            aqjkNowApiData = new ArrayList<>();
//        }
//        //转成map
//        Map<String, OtherApiAqjkNowDto> otherApiAqjkNowDtoMap = aqjkNowApiData.stream().collect(Collectors.toMap(OtherApiAqjkNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiAqjkNowDto())));
//
//        //获取华能龙软映射表信息
//        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");
//        // 需要删除的煤矿编码列表 魏家峁 铧尖 伊敏
//        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList);
//
//        List<MineCodeMapDto> onlineList = new ArrayList<>();
//        List<MineCodeMapDto> offlineList = new ArrayList<>();
//        List<MineCodeMapDto> awaitList = new ArrayList<>();
//        for (MineCodeMapDto mineCodeMapDto : mineCodeMapList) {
//            if ("150621011038".equals(mineCodeMapDto.getMineCode())) {
//                //如果是高头窑 获取高头窑的数据
//                List<PointStatistics> pointStatistics = safetyMonitorService.pointStatistics(mineCodeMapDto.getMineCode());
//                if (!pointStatistics.isEmpty()) {
//                    onlineList.add(mineCodeMapDto);
//                } else {
//                    offlineList.add(mineCodeMapDto);
//                }
//                continue;
//            }
//            if (StringUtils.isEmpty(mineCodeMapDto.getMineId())) {
//                awaitList.add(mineCodeMapDto);
//                //终止本次，开始处理下一次循环
//                continue;
//            }
//            //可以获取到龙软的信息 代表在线
//            if (otherApiAqjkNowDtoMap.get(mineCodeMapDto.getMineId()) != null && otherApiAqjkNowDtoMap.get(mineCodeMapDto.getMineId()).getSensorCount() > 0) {
//                //有数据信息  在线
//                onlineList.add(mineCodeMapDto);
//            } else {
//                offlineList.add(mineCodeMapDto);
//            }
//
//        }
        OnLineMineInfoVo onLineMineInfoVo = new OnLineMineInfoVo();
        //在线煤矿数
//        onLineMineInfoVo.setOnlineNumber(onlineList.size());
        onLineMineInfoVo.setOnlineNumber(23);
        //在线煤矿列表
//        onLineMineInfoVo.setOnlineList(onlineList);
        onLineMineInfoVo.setOnlineList(new ArrayList<>());

        //中断煤矿数
//        onLineMineInfoVo.setOfflineNumber(offlineList.size());
        onLineMineInfoVo.setOfflineNumber(0);
        onLineMineInfoVo.setOfflineList(new ArrayList<>());

        //待接入煤矿数
//        onLineMineInfoVo.setAwaitNumber(awaitList.size());
        onLineMineInfoVo.setAwaitNumber(0);
//        onLineMineInfoVo.setAwaitList(awaitList);
        onLineMineInfoVo.setAwaitList(new ArrayList<>());
        return onLineMineInfoVo;
    }

    /**
     * 获取龙软（井工矿）报警数据（甲烷和一氧化碳报警）入库
     * @return
     */
    public MineDataResponse<List<OtherApiAqjkNowDto>> getLongRuanAlarmList() {
        //获取龙软煤矿数据
        MineDataResponse<List<OtherApiAqjkNowDto>> otherSystemGroupAqjkNowApi = this.getOtherSystemGroupAqjkNowApi();
        if (!otherSystemGroupAqjkNowApi.isSuccess()) {
            //获取数据没有成功
            return new MineDataResponse<>();
        } else {
            //获取数据成功
            //保存在中间表中
            List<OtherApiAqjkNowDto> data = otherSystemGroupAqjkNowApi.getData();
//            //获取龙软安全监控测点接口
//            MineDataResponse<OtherApiAqjkNowCountDto> otherSystemGroupAqjkCountNowApi = this.getOtherSystemGroupAqjkCountNowApi();
//            Integer coAlarmCount = 0;
//            Integer ch4AlarmCount = 0;
//            if (otherSystemGroupAqjkCountNowApi.isSuccess()) {
//                OtherApiAqjkNowCountDto otherApiAqjkNowCountDto = otherSystemGroupAqjkCountNowApi.getData();
//                coAlarmCount = otherApiAqjkNowCountDto.getCoCount();
//                ch4AlarmCount = otherApiAqjkNowCountDto.getGasCount();
//            }
            //获取现在的时间
//            LocalDateTime now = LocalDateTime.now();
            Date now = new Date();
            if (!data.isEmpty()) {
//                Integer finalCoAlarmCount = coAlarmCount;
//                Integer finalCh4AlarmCount = ch4AlarmCount;
                List<LongruanAlarmListPo> collect = data.stream().map(t -> {
                    LongruanAlarmListPo longruanAlarmListPo = new LongruanAlarmListPo();

                    longruanAlarmListPo.setMineId(t.getMineID());
                    longruanAlarmListPo.setMineName(t.getMineName());
                    //测点总数
                    longruanAlarmListPo.setSensorCount(t.getSensorCount());
                    //一氧化碳报警数
                    longruanAlarmListPo.setCoWarnCount(t.getCoWarnCount());
                    //一氧化碳测点数
//                    longruanAlarmListPo.setCoCount(finalCoAlarmCount);
                    //甲烷报警数
                    longruanAlarmListPo.setCh4WarnCount(t.getCH4WarnCount());
                    //甲烷测点数
//                    longruanAlarmListPo.setCh4Count(finalCh4AlarmCount);
                    //报警总数
                    longruanAlarmListPo.setWarnCount(t.getWarnCount());
                    //数据时间
                    longruanAlarmListPo.setDataTime(now);
                    return longruanAlarmListPo;
                }).collect(Collectors.toList());
                for (LongruanAlarmListPo longruanAlarmListPo : collect) {
                    longruanAlarmListMapper.insert(longruanAlarmListPo);
                }
            }

        }
        return otherSystemGroupAqjkNowApi;
    }

    /**
     * getSafetyMonitoringLocl
     * @return
     */
    public SafetyMonitoringVo getSafetyMonitoringLocl() {
        //获取龙软本地数据
       List<LongruanAlarmListPo> list =longruanAlarmListMapper.selectMaxDateList();
        if (list.isEmpty()) {
            return new SafetyMonitoringVo();
        }
        List<OtherApiAqjkNowDto> aqjkNowApiData = list.stream().map(t -> {
            OtherApiAqjkNowDto otherApiAqjkNowDto = new OtherApiAqjkNowDto();
            otherApiAqjkNowDto.setMineID(t.getMineId());
            otherApiAqjkNowDto.setMineName(t.getMineName());
            otherApiAqjkNowDto.setSensorCount(t.getSensorCount());
            otherApiAqjkNowDto.setWarnCount(t.getWarnCount());
            otherApiAqjkNowDto.setCoWarnCount(t.getCoWarnCount());
            otherApiAqjkNowDto.setCH4WarnCount(t.getCh4WarnCount());
            return otherApiAqjkNowDto;
        }).collect(Collectors.toList());

        //转成map
        Map<String, OtherApiAqjkNowDto> otherApiAqjkNowDtoMap = aqjkNowApiData.stream().collect(Collectors.toMap(OtherApiAqjkNowDto::getMineID, p -> Optional.ofNullable(p).orElse(new OtherApiAqjkNowDto())));

        //获取华能龙软映射表信息
        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");

        // 需要删除的煤矿编码列表（去除露天矿） 魏家峁 铧尖 伊敏
        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList);

        //20240721 需要删除的煤矿编码列表（去除特殊煤矿）：马蹄沟 620824009852，刘园子 621022009406
//        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList, Arrays.asList("620824009852,621022009406"));
        //去除马蹄沟的数据：620824009852
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("620824009852"))
                .collect(Collectors.toList());
        //去除 刘园子 621022009406
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("621022009406"))
                .collect(Collectors.toList());

        //去除 测点数为零的煤矿
        mineCodeMapList = mineCodeMapList.stream().filter(t -> {
            //获取龙软数据
            OtherApiAqjkNowDto otherApiAqjkNowDto = otherApiAqjkNowDtoMap.get(t.getMineId());
            if (otherApiAqjkNowDto != null  && otherApiAqjkNowDto.getSensorCount() > 0) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        //煤矿报警列表
        List<MinePointInAlarmfoVo> minePointInAlarmfoVoList = mineCodeMapList.stream().map(t -> {
            MinePointInAlarmfoVo minePointInAlarmfoVo = new MinePointInAlarmfoVo();
            minePointInAlarmfoVo.setMineCode(t.getMineCode());
            minePointInAlarmfoVo.setMineName(t.getMineName());
            //龙软煤矿数据
            OtherApiAqjkNowDto otherApiAqjkNowDto = otherApiAqjkNowDtoMap.get(t.getMineId());
            if (otherApiAqjkNowDto != null) {
                //TODO 屏蔽掉雨汪煤矿（10105087403）和新庄煤矿（01001002014）的报警值
                if ("10105087403".equals(otherApiAqjkNowDto.getMineID()) || "01001002014".equals(otherApiAqjkNowDto.getMineID())) {
                    otherApiAqjkNowDto.setCoWarnCount(0);
                    otherApiAqjkNowDto.setCH4WarnCount(0);

                }
                //设置测点数据
                minePointInAlarmfoVo.setPointNumber(otherApiAqjkNowDto.getSensorCount());
                minePointInAlarmfoVo.setCH4WarnCount(otherApiAqjkNowDto.getCH4WarnCount());
                minePointInAlarmfoVo.setCoWarnCount(otherApiAqjkNowDto.getCoWarnCount());
                minePointInAlarmfoVo.setRemark(t.getMineId());
            } else {
                //查询华能的报警数据
                List<PointStatistics> pointStatistics = safetyMonitorService.pointStatistics(t.getMineCode());
                if (pointStatistics.isEmpty()) {
                    //如果是空值 则设置默认值为零
                    minePointInAlarmfoVo.setPointNumber(0);
                    minePointInAlarmfoVo.setCH4WarnCount(0);
                    minePointInAlarmfoVo.setCoWarnCount(0);
                    minePointInAlarmfoVo.setRemark(t.getMineCode());
                } else {
                    //获取甲烷信息。
                    //转成map
                    //环境瓦斯	54	0
                    //氧气	10	0
                    //烟雾	17	0
                    //粉尘	6	0
                    //风速	7	0
                    //湿度	2	0
                    //一氧化碳	50	0
                    //环境温度	51	0
                    Map<String, PointStatistics> pointStatisticsMap = pointStatistics.stream().collect(Collectors.toMap(PointStatistics::getType, p -> Optional.ofNullable(p).orElse(new PointStatistics())));

                    //获取甲烷信息
                    PointStatistics pointStatisticsItemCH4 = pointStatisticsMap.get("环境瓦斯");
                    if (pointStatisticsItemCH4 == null) {
                        pointStatisticsItemCH4 = new PointStatistics();
                    }
                    //设置甲烷数
                    minePointInAlarmfoVo.setCH4WarnCount(Optional.ofNullable(pointStatisticsItemCH4.getAlarmCount()).orElse(0));
                    //获取一氧化碳信息
                    PointStatistics pointStatisticsItemCO = pointStatisticsMap.get("一氧化碳");
                    if (pointStatisticsItemCO == null) {
                        pointStatisticsItemCO = new PointStatistics();
                    }
                    minePointInAlarmfoVo.setCoWarnCount(Optional.ofNullable(pointStatisticsItemCO.getAlarmCount()).orElse(0));
                    //设置测点总数   甲烷测点数+一氧化碳测点数
                    int sum = pointStatisticsItemCH4.getPointCount() + pointStatisticsItemCO.getPointCount();
                    minePointInAlarmfoVo.setPointNumber(sum);
                    minePointInAlarmfoVo.setRemark(t.getMineCode()+
                            "-"+pointStatisticsItemCH4.getType()+":"+pointStatisticsItemCH4.getPointCount()+
                            "-"+pointStatisticsItemCO.getType()+":"+pointStatisticsItemCO.getPointCount());
                }

            }

            return minePointInAlarmfoVo;
        }).collect(Collectors.toList());

        //计算测点总数
        int pointNumberSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getPointNumber)
                .sum();

        //计算CH4超限数
        int cH4WarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCH4WarnCount)
                .sum();
        //计算CO超限数
        int coWarnCountSum = minePointInAlarmfoVoList.stream()
                .mapToInt(MinePointInAlarmfoVo::getCoWarnCount)
                .sum();

        SafetyMonitoringVo vo = new SafetyMonitoringVo();

        //获取龙软安全监控测点接口
        MineDataResponse<OtherApiAqjkNowCountDto> otherSystemGroupAqjkCountNowApi = this.getOtherSystemGroupAqjkCountNowApi();

        OtherApiAqjkNowCountDto otherApiAqjkNowCountDto = otherSystemGroupAqjkCountNowApi.getData();
        if (otherApiAqjkNowCountDto != null) {
            vo.setCH4Number(otherApiAqjkNowCountDto.getGasCount());
            vo.setCoNumber(otherApiAqjkNowCountDto.getCoCount());
        } else {
            //CH4测点数
            vo.setCH4Number(0);
            //CO测点数
            vo.setCoNumber(0);
        }
        //煤矿测点信息列表
        vo.setMinePointInAlarmfoList(minePointInAlarmfoVoList);
        //测点总数
        vo.setPonitSum(pointNumberSum);
        //CH4超限报警数
        vo.setCH4WarnCount(cH4WarnCountSum);
//        vo.setCH4WarnCount(0);
        //CO超限报警数
        vo.setCoWarnCount(coWarnCountSum);
//        vo.setCoWarnCount(0);
        return vo;
    }

    /**
     * 大屏首页-主通风详情
     * @return
     */
    public List<FanSystemVolumeAndSpeedVo> getFanSystemInfoList() {
        List<FanSystemVolumeAndSpeedVo> fanSystemVolumeAndSpeedVos = new ArrayList<>();

        //获取华能龙软映射表信息
        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");

        // 需要删除的煤矿编码列表（去除露天矿） 魏家峁 铧尖 伊敏
        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList);
        //根据煤矿编码查询煤矿主通风详情


        //20240721 需要删除的煤矿编码列表（去除特殊煤矿）：马蹄沟 620824009852，刘园子 621022009406
//        mineCodeMapList = getRemoveMineCodeList(mineCodeMapList, Arrays.asList("620824009852,621022009406"));
        //去除马蹄沟的数据：620824009852
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("620824009852"))
                .collect(Collectors.toList());
        //去除 刘园子 621022009406
        mineCodeMapList = mineCodeMapList.stream()
                .filter(dto -> !dto.getMineCode().equals("621022009406"))
                .collect(Collectors.toList());

        mineCodeMapList.forEach(t -> {
            String mineCode = t.getMineCode();
            String mineName = t.getMineName();
            R<List<FanSystemVolumeAndSpeedDto>> fanSystemVolumeAndSpeedList = remoteEquipmentService.getFanSystemVolumeAndSpeedList(mineCode);
            //如果获取不到数据
            if (fanSystemVolumeAndSpeedList.getCode()==Constants.FAIL || fanSystemVolumeAndSpeedList.getData().isEmpty()) {
                FanSystemVolumeAndSpeedVo fanSystemVolumeAndSpeedVo = new FanSystemVolumeAndSpeedVo();
                fanSystemVolumeAndSpeedVo.setMineCode(mineCode);
                fanSystemVolumeAndSpeedVo.setMineName(mineName);
                fanSystemVolumeAndSpeedVo.setLocation("---");
                fanSystemVolumeAndSpeedVo.setDeviceDtoList(new ArrayList<>());
                fanSystemVolumeAndSpeedVos.add(fanSystemVolumeAndSpeedVo);
            }else {
                List<FanSystemVolumeAndSpeedDto> data = fanSystemVolumeAndSpeedList.getData();

                if ("620824009734".equals(mineCode)) {
                    //对研北数据特殊处理 屏蔽局扇数据
                    data=data.stream().filter(t1 -> !t1.getDeviceName().contains("局扇")).collect(Collectors.toList());
                }


                //根据机房分组
                Map<String, List<FanSystemVolumeAndSpeedDto>> collect = data.stream().collect(Collectors.groupingBy(FanSystemVolumeAndSpeedDto::getLocation));
                collect.forEach((k, v) -> {
                    //创建返回数据集合
                    FanSystemVolumeAndSpeedVo fanSystemVolumeAndSpeedVo = new FanSystemVolumeAndSpeedVo();
                    fanSystemVolumeAndSpeedVo.setMineCode(mineCode);
                    fanSystemVolumeAndSpeedVo.setMineName(mineName);
                    fanSystemVolumeAndSpeedVo.setLocation(v.get(0).getLocation());

                    //设备详情
                    List<FanSystemDeviceDto> fanSystemDeviceDtos = new ArrayList<>();
                    v.forEach(t1 -> {
                        FanSystemDeviceDto fanSystemDeviceDto = new FanSystemDeviceDto();
                        fanSystemDeviceDto.setDeviceName(t1.getDeviceName());
                        fanSystemDeviceDto.setSpeed(t1.getSpeed());
                        fanSystemDeviceDto.setVolume(t1.getVolume());
                        fanSystemDeviceDto.setStatus(t1.getStatus());
                        fanSystemDeviceDtos.add(fanSystemDeviceDto);
                    });
                    fanSystemVolumeAndSpeedVo.setDeviceDtoList(fanSystemDeviceDtos);
                    fanSystemVolumeAndSpeedVos.add(fanSystemVolumeAndSpeedVo);
                });
            }
        });

        return fanSystemVolumeAndSpeedVos;
    }

    /**
     * 大屏首页-煤矿地质-水害地质类型列表
     * @return
     */
    public GeologyMineListVO getMineHazardTypeHydrologyList(String companyCode, String mineCode) {
        //获取煤矿信息
        List<DimCoalMineBasicInfoVo> dimCoalMineBasicInfoVos = dwsService.selectDisasterList(companyCode,mineCode).getData();


        GeologyMineListVO geologyMineListVO = new GeologyMineListVO();

        //筛选过滤信息  查找包含水文的煤矿
        List<DimCoalMineBasicInfoVo> hydrologyList = dimCoalMineBasicInfoVos.stream().filter(t -> t.getMineDisasterTypes().contains("水文")).collect(Collectors.toList());
        //筛选过滤信息  查找包含水文极复杂的煤矿
        List<DimCoalMineBasicInfoVo> LevelComplexHydrologyList = hydrologyList.stream().filter(t -> t.getMineDisasterTypes().contains("水文极复杂")).collect(Collectors.toList());
        geologyMineListVO.setLevelComplex(LevelComplexHydrologyList.size());
        geologyMineListVO.setLevelComplexMineList(LevelComplexHydrologyList);

        //筛选过滤信息  查找包含水文复杂的煤矿
        List<DimCoalMineBasicInfoVo> complexHydrologyList = hydrologyList.stream().filter(t -> t.getMineDisasterTypes().contains("水文复杂")).collect(Collectors.toList());
        geologyMineListVO.setComplex(complexHydrologyList.size());
        geologyMineListVO.setComplexMineList(complexHydrologyList);

        //筛选过滤信息  查找包含水文中等的煤矿
        List<DimCoalMineBasicInfoVo> moderateHydrologyList = hydrologyList.stream().filter(t -> t.getMineDisasterTypes().contains("水文中等")).collect(Collectors.toList());
        geologyMineListVO.setModerate(moderateHydrologyList.size());
        geologyMineListVO.setModerateMineList(moderateHydrologyList);


        //筛选过滤信息  查找包含水文简单的煤矿
        List<DimCoalMineBasicInfoVo> simpleHydrologyList = hydrologyList.stream().filter(t -> t.getMineDisasterTypes().contains("水文简单")).collect(Collectors.toList());
        geologyMineListVO.setSimple(simpleHydrologyList.size());
        geologyMineListVO.setSimpleMineList(simpleHydrologyList);


        return geologyMineListVO;
    }

    /**
     * 瓦斯等级列表
     * @return
     */
    public GassyMineListVO getMineGassyMineList(String companyCode, String mineCode) {
        //获取煤矿信息
        List<DimCoalMineBasicInfoVo> dimCoalMineBasicInfoVos = dwsService.selectDisasterList(companyCode,mineCode).getData();
        GassyMineListVO gassyMineListVO = new GassyMineListVO();

        //获取华能龙软映射表信息
//        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");
        //筛选过滤信息  查找包含瓦斯的煤矿
        List<DimCoalMineBasicInfoVo> gassyList = dimCoalMineBasicInfoVos.stream().filter(t -> t.getMineDisasterTypes().contains("瓦斯")).collect(Collectors.toList());

        //筛选过滤信息  查找包含瓦斯高瓦斯矿井的煤矿
        List<DimCoalMineBasicInfoVo> highGasMineList = gassyList.stream().filter(t -> t.getMineDisasterTypes().contains("高瓦斯")).collect(Collectors.toList());
        gassyMineListVO.setHighGasMine(highGasMineList.size());
        gassyMineListVO.setHighGasMineList(highGasMineList);

        //筛选过滤信息  查找包含瓦斯低瓦斯矿井的煤矿
        List<DimCoalMineBasicInfoVo> lowGasMineList = gassyList.stream().filter(t -> t.getMineDisasterTypes().contains("低瓦斯")).collect(Collectors.toList());
        gassyMineListVO.setLowGasMine(lowGasMineList.size());
        gassyMineListVO.setLowGasMineList(lowGasMineList);
        //筛选过滤信息  查找包含瓦斯突出矿井的煤矿
        List<DimCoalMineBasicInfoVo> extrudeMineList = gassyList.stream().filter(t -> t.getMineDisasterTypes().contains("瓦斯突出")).collect(Collectors.toList());
        gassyMineListVO.setExtrudeMine(extrudeMineList.size());
        gassyMineListVO.setExtrudeMineList(extrudeMineList);


        return gassyMineListVO;
    }

    /**
     * 冲击地压危险等级列表
     * @return
     */
    public ImpactMineListVO getMineImpactMineList(String companyCode, String mineCode) {
        //获取煤矿信息
        List<DimCoalMineBasicInfoVo> dimCoalMineBasicInfoVos = dwsService.selectDisasterList(companyCode,mineCode).getData();
        ImpactMineListVO impactMineListVO = new ImpactMineListVO();
        //获取华能龙软映射表信息
//        List<MineCodeMapDto> mineCodeMapList = remoteMineInfoService.getMineCodeMapList("");
        //筛选过滤信息  查找包含冲击的煤矿
        List<DimCoalMineBasicInfoVo> impactList = dimCoalMineBasicInfoVos.stream().filter(t -> t.getMineDisasterTypes().contains("冲击")).collect(Collectors.toList());
        //筛选过滤信息  查找包含强冲击的煤矿
        List<DimCoalMineBasicInfoVo> strongImpactList = impactList.stream().filter(t -> t.getMineDisasterTypes().contains("强冲击")).collect(Collectors.toList());
        impactMineListVO.setStrong(strongImpactList.size());
        impactMineListVO.setStrongMineList(strongImpactList);
        //筛选过滤信息  查找包含中等冲击的煤矿
        List<DimCoalMineBasicInfoVo> mediumImpactList = impactList.stream().filter(t -> t.getMineDisasterTypes().contains("中等冲击")).collect(Collectors.toList());
        impactMineListVO.setMedium(mediumImpactList.size());
        impactMineListVO.setMediumMineList(mediumImpactList);
        //筛选过滤信息  查找包含弱冲击的煤矿
        List<DimCoalMineBasicInfoVo> weakImpactList = impactList.stream().filter(t -> t.getMineDisasterTypes().contains("弱冲击")).collect(Collectors.toList());
        impactMineListVO.setWeak(weakImpactList.size());
        impactMineListVO.setWeakMineList(weakImpactList);
        //筛选过滤信息  查找包含有冲击倾向的煤矿
        List<DimCoalMineBasicInfoVo> tendencyImpactList = impactList.stream().filter(t -> t.getMineDisasterTypes().contains("冲击倾向")).collect(Collectors.toList());
        impactMineListVO.setTendency(tendencyImpactList.size());
        impactMineListVO.setTendencyMineList(tendencyImpactList);

        return impactMineListVO;
    }
}
